package com.bytech.common.config;

import java.util.HashSet;
import java.util.Set;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @Author zhao
 * @Create 2021/7/20 22:42
 */
@EnableCaching
@Configuration
@Slf4j
@RefreshScope
public class RedisConfig {

    @Value("${redis.cluster.host}")
    private String clusterHost;
    @Value("${redis.cluster.nodes}")
    private String clusterNodes;
    @Value("${redis.password}")
    private String password;
    @Value("${redis.pool.max-total}")
    private Integer maxTotal;
    @Value("${redis.pool.max-wait}")
    private Long maxWait;
    @Value("${redis.pool.max-idle}")
    private Integer maxIdle;
    @Value("${redis.pool.min-idle}")
    private Integer minIdle;
    @Value("${redis.timeout}")
    private Integer timeout;
    @Value("${redis.soTimeout}")
    private Integer soTimeout;
    @Value("${redis.maxAttempts}")
    private Integer maxAttempts;

    @Bean
    public JedisCluster jedisCluster() {
        return new JedisCluster(getNodes(), timeout, soTimeout, maxAttempts, password, poolConfig());
    }

    private JedisPoolConfig poolConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        config.setMaxTotal(maxTotal);
        config.setMaxWaitMillis(maxWait);
        return config;
    }

    private Set<HostAndPort> getNodes() {
        String[] cNodes = clusterNodes.split(",");
        Set<HostAndPort> nodes = new HashSet<>();
        for (String node : cNodes) {
            nodes.add(new HostAndPort(clusterHost, Integer.parseInt(node)));
        }
        return nodes;
    }

    private Set<HostAndPort> getIP6Nodes() {
        log.info("init redis cluster nodes with host:" + clusterHost + " nodes:" + clusterNodes);
        String[] cNodes = clusterNodes.split(",");
        Set<HostAndPort> nodes = new HashSet<HostAndPort>();
        // 构造集群节点
        String[] hp;
        for (String nodePort : cNodes) {
            nodes.add(new HostAndPort(String.format("[%s]", clusterHost), Integer.parseInt(nodePort)));
        }
        return nodes;
    }
}
